package com.shuqi.model.manager;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;

import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.LoginHelper;
import com.shuqi.common.MyTask;
import com.shuqi.common.Urls;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.Util;
import com.shuqi.database.dao.impl.BookCataLogDao;
import com.shuqi.database.dao.impl.BookInfoDao;
import com.shuqi.database.dao.impl.BookMarkInfoDao;
import com.shuqi.database.model.BookCataLog;
import com.shuqi.database.model.BookInfo;
import com.shuqi.database.model.BookMarkInfo;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.model.bean.BookData;
import com.shuqi.model.net.HttpRequest;
import com.shuqi.model.net.UrlManager;
import com.shuqi.model.net.listener.HttpRequestListener;
import com.shuqi.model.parse.parser.PayDownCatalogParser;
import com.shuqi.model.parse.parser.YiSoDownCatalogParser;

/**
 * 
 * 书籍目录管理 目录获取，目录下载，目录更新等操作
 * 
 * @author hxp
 * @date 2014-3-9
 * 
 */
public class BookCatalogManager {

    /**
     * 根据页码 和 页大小 获取神马某本书的目录信息
     * 
     * @param bookId
     * @param sourceId
     * @param uid
     * @param vid
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public static BookData getCatalogSMByPageIndex(String bookId, String sourceId, String uid,
            String vid, int pageIndex, int pageSize) {
        return getCatalogByPageIndex(bookId, sourceId, uid, vid, pageIndex, pageSize,
                BookMarkInfo.TYPE_NEW_SHENMA_BOOKMARK);
    }

    /**
     * 根据页码 和 页大小 获取书旗某本书的目录信息
     * 
     * @param bookId
     * @param uid
     * @param vid
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public static BookData getCatalogSQByPageIndex(String bookId, String uid, String vid,
            int pageIndex, int pageSize) {
        return getCatalogByPageIndex(bookId, "", uid, vid, pageIndex, pageSize,
                BookMarkInfo.TYPE_NEW_PAY_BOOKMARK);
    }

    /**
     * 根据BookId 和 SourceId 获取整本书的目录信息
     * 
     * @param bookId
     * @param sourceId
     * @param uid
     * @return
     */
    public static BookData getBookCatalogByBidAndSid(final String bookId, final String sourceId,
            final String uid, int bookType) {
        final List<BookCataLog> catalogList = new ArrayList<BookCataLog>();
        List<BookCataLog> daoTemplogList =
                BookCataLogDao.getInstance().getAllCatalog(uid, bookId, sourceId);
        if (daoTemplogList != null && daoTemplogList.size() > 0) {
            catalogList.addAll(daoTemplogList);
        }

        if (catalogList.size() <= 0) {// 数据库没有数据，开启网络下载（该下载未开线程）
            DownLoadListener downLoadListener = new DownLoadListener() {
                @Override
                public void onLoadSucess(BookData bookData) {
                    if (bookData != null && bookData.getInfos() != null) {
                        List<BookCataLog> netTemplogList =
                                BookCataLogDao.getInstance().getAllCatalog(uid, bookId, sourceId);
                        if (netTemplogList != null && netTemplogList.size() > 0) {
                            catalogList.addAll(netTemplogList);
                        }
                    }
                }

                @Override
                public void onLoadFaild() {

                }
            };
            syncDownloadCatalog(bookId, sourceId, uid, bookType, downLoadListener);
        }

        if (catalogList.size() <= 0) { // 数据库没有数据，同时网络下载失败
            return null;
        }

        BookInfo bookInfo = BookInfoDao.getInstance().getBookInfo(sourceId, bookId, uid);
        if (bookInfo != null) {// 判断书籍信息不为空
            BookData bookData = new BookData();
            bookData.setAuthorName(bookInfo.getBookAuthorName());
            bookData.setBookId(bookId);
            bookData.setSourceId(sourceId);
            bookData.setBookName(bookInfo.getBookName());
            bookData.setCoverImg(bookInfo.getBookCoverImgUrl());
            bookData.setHide(bookInfo.getBookHideState());
            bookData.setCoverIsopen(bookInfo.getCoverHideState());
            bookData.setReadIsopen(bookInfo.getReadHideState());
            bookData.setOidMax(bookInfo.getBookMaxOid());
            bookData.setWordCount(bookInfo.getBookWordCount());
            bookData.setInfos(catalogList);
            return bookData;
        }
        return null; // 书籍信息为空
    }


    /**
     * 
     * @param bookId
     * @param sourceId
     * @param uid
     * @param vid
     * @param pageIndex
     * @param pageSize
     * @return
     */
    private static BookData getCatalogByPageIndex(final String bookId, final String sourceId,
            final String uid, final String vid, final int pageIndex, final int pageSize,
            int bookType) {
        final List<BookCataLog> catalogList = new ArrayList<BookCataLog>();
        List<BookCataLog> daoTemplogList =
                BookCataLogDao.getInstance().getCatalogByPageIndex(bookId, sourceId, uid, vid,
                        pageIndex, pageSize);
        if (daoTemplogList != null && daoTemplogList.size() > 0) {
            catalogList.addAll(daoTemplogList);
        }

        if (catalogList.size() <= 0) {// 数据库没有数据，开启网络下载（该下载未开线程）
            DownLoadListener downLoadListener = new DownLoadListener() {
                @Override
                public void onLoadSucess(BookData bookData) {
                    if (bookData != null && bookData.getInfos() != null) {
                        List<BookCataLog> netTemplogList =
                                BookCataLogDao.getInstance().getCatalogByPageIndex(bookId,
                                        sourceId, uid, vid, pageIndex, pageSize);
                        if (netTemplogList != null && netTemplogList.size() > 0) {
                            catalogList.addAll(netTemplogList);
                        }
                    }
                }

                @Override
                public void onLoadFaild() {

                }
            };
            syncDownloadCatalog(bookId, sourceId, uid, bookType, downLoadListener);
        }

        if (catalogList.size() <= 0) { // 数据库没有数据，同时网络下载失败
            return null;
        }

        BookInfo bookInfo = BookInfoDao.getInstance().getBookInfo(sourceId, bookId, uid);

        if (bookInfo != null) {// 判断书籍信息不为空
            long count =
                    BookCataLogDao.getInstance()
                            .getChapterCountOfVolume(uid, bookId, sourceId, vid);
            BookData bookData = new BookData();
            bookData.setAuthorName(bookInfo.getBookAuthorName());
            bookData.setBookId(bookId);
            bookData.setSourceId(sourceId);
            bookData.setBookName(bookInfo.getBookName());
            bookData.setCoverImg(bookInfo.getBookCoverImgUrl());
            bookData.setHide(bookInfo.getBookHideState());
            bookData.setCoverIsopen(bookInfo.getCoverHideState());
            bookData.setReadIsopen(bookInfo.getReadHideState());
            bookData.setOidMax(bookInfo.getBookMaxOid());
            bookData.setWordCount(bookInfo.getBookWordCount());
            long pageCount = 1;
            if (pageSize != 0) {
                pageCount = count / pageSize == 0 ? count / pageSize : count / pageSize + 1;
            }
            bookData.setPageCount((int) pageCount);
            bookData.setInfos(catalogList);
            return bookData;
        }
        return null; // 书籍信息为空
    }

    /**
     * 同步下载书籍目录信息
     * 
     * @param bookId
     * @param sourceId
     * @param uid
     * @param bookType
     */
    public static void syncDownloadCatalog(String bookId, String sourceId, final String uid,
            int bookType, DownLoadListener downLoadListener) {
        if (bookType == BookMarkInfo.TYPE_OLD_ONLINE_BOOKMARK
                || bookType == BookMarkInfo.TYPE_NEW_PAY_BOOKMARK) {
            downloadShuQiCatalogOnline(bookId, sourceId, uid, downLoadListener, true);

        } else if (bookType == BookMarkInfo.TYPE_NEW_SHENMA_BOOKMARK) {
            downloadYiSouCatalogOnline(bookId, sourceId, uid, downLoadListener, true);
        }
    }

    public static void asyncDownloadCatalog(String bookId, String sourceId, final String uid,
            int bookType) {
        DownLoadListener downLoadListener = new DownLoadListener() {
            @Override
            public void onLoadSucess(BookData bookData) {
                if (bookData != null && bookData.getInfos() != null) {
                    Log4an.i("yjd", "更新目录成功");
                }
            }

            @Override
            public void onLoadFaild() {
                Log4an.i("yjd", "更新目录失败");
            }
        };
        if (bookType == BookMarkInfo.TYPE_OLD_ONLINE_BOOKMARK
                || bookType == BookMarkInfo.TYPE_NEW_PAY_BOOKMARK) {
            Log4an.i("yjd", "开始更新书旗目录");
            downloadShuQiCatalogOnline(bookId, sourceId, uid, downLoadListener, false);

        } else if (bookType == BookMarkInfo.TYPE_NEW_SHENMA_BOOKMARK) {
            downloadYiSouCatalogOnline(bookId, sourceId, uid, downLoadListener, false);
        }
    }

    /** 异步下载书籍目录 */
    public static void downloadShuQiCatalog(String bookId, final String uid,
            DownLoadListener downLoadListener) {
        downloadShuQiCatalogOnline(bookId, "", uid, downLoadListener, false);
    }



    /**
     * 
     * 保存或更新书籍数据 （书籍表 和 对应目录表）
     * 
     * @param bookData
     * @param uid
     */
    private static void saveOrUpdateBookData(BookData bookData, String uid) {
        BookInfo bookInfo = new BookInfo();
        bookInfo.setBookId(bookData.getBookId());
        bookInfo.setSourceId(bookData.getSourceId());
        bookInfo.setBookName(bookData.getBookName());
        bookInfo.setBookAuthorName(bookData.getAuthorName());
        bookInfo.setBookCoverImgUrl(bookData.getCoverImg());
        bookInfo.setBookMaxOid(bookData.getOidMax());
        bookInfo.setBookWordCount(bookData.getWordCount());
        bookInfo.setBookHideState(bookData.getHide());
        bookInfo.setCoverHideState(bookData.getCoverIsopen());
        bookInfo.setReadHideState(bookData.getReadIsopen());
        bookInfo.setUpdateCatalog(BookInfo.UPDATE_CATALOG_NO);
        bookInfo.setBookPayMode(bookData.getPayMode());
        bookInfo.setUserId(uid);
        int num = BookInfoDao.getInstance().saveOrUpdateBookInfo(bookInfo);
        Log4an.i("updatacatalog", "saveOrUpdateBookData num = " + num);

        BookCataLogDao.getInstance().saveOrUpdateCatalog(uid, bookData.getBookId(),
                bookData.getSourceId(), bookData.getInfos());
    }


    /**
     * 联网获取书旗章节目录
     * 
     * @param bookId
     * @param sourceId
     * @param uid
     */
    private static void downloadShuQiCatalogOnline(final String bookId, final String sourceId,
            final String uid, final DownLoadListener downLoadListener, boolean isSync) {
        HttpRequestListener httpRequsetListener = new HttpRequestListener() {
            @Override
            public List<BasicNameValuePair> setParams() {
                List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
                String timestamp = String.valueOf(System.currentTimeMillis());

                String strTimestamp = timestamp + uid;
                String md5_key = Util.getMD5(LoginHelper.Encrypt(strTimestamp));
                params.add(new BasicNameValuePair("PostTime", timestamp));// 时间戳
                params.add(new BasicNameValuePair("PostToken", md5_key));// md5
                /** 7系升8系收费书籍免费看添加验证 */
                BookMarkInfo markInfo =
                        BookMarkInfoDao.getInstance().getBookMark(sourceId, bookId, uid,
                                BookMarkInfo.TYPE_OLD_ONLINE_BOOKMARK);
                if (markInfo != null) {
                    String key = "37e81a9d8f02596e1b895d07c171d5c9";
                    String mdkey = Util.getMD5(uid + bookId);
                    String readKeyStrs = mdkey + key + timestamp;
                    String readKey = Util.getMD5(readKeyStrs);
                    params.add(new BasicNameValuePair("readKey", readKey));
                }
                return params;
            }

            @Override
            public String getRequestUrl() {
                return Urls.getPayCatalogUrl(uid, bookId);
            }

            @Override
            public void action(int actionCode, Object object) {
                if (actionCode == EventTypeConstants.EVENT_SUCCESS) {
                    if (object != null) {
                        BookData data = (BookData) object;
                        saveOrUpdateBookData(data, uid);
                        if (downLoadListener != null) {
                            downLoadListener.onLoadSucess(data);
                            return;
                        }
                    }
                }
                // 通知失败
                if (downLoadListener != null) {
                    downLoadListener.onLoadFaild();
                }
            }
        };
        HttpRequest request =
                new HttpRequest(ShuqiApplication.getContext(), UrlManager.COLUMN_DOMAIN_READ,
                        httpRequsetListener.getRequestUrl(), httpRequsetListener.setParams(),
                        httpRequsetListener);
        final PayDownCatalogParser catalogParser = new PayDownCatalogParser(bookId, sourceId, uid);
        request.setDataParseAdapter(catalogParser);
        if (isSync) {
            request.run();
        } else {
            MyTask.runInBackground(request, true);
        }
    }


    /**
     * 
     * 联网获取一搜章节目录
     * 
     * @param sourceId
     * @param bookId
     * @param uid
     */
    private static void downloadYiSouCatalogOnline(final String bookId, final String sourceId,
            final String uid, final DownLoadListener downLoadListener, boolean isSync) {

        HttpRequestListener httpRequsetListener = new HttpRequestListener() {
            @Override
            public List<BasicNameValuePair> setParams() {
                return null;
            }

            @Override
            public String getRequestUrl() {
                return Urls.getYiSouCatalogUrl(uid, sourceId, bookId);
            }

            @Override
            public void action(int actionCode, Object object) {
                if (actionCode == EventTypeConstants.EVENT_SUCCESS) {
                    if (object != null) {
                        BookData data = (BookData) object;
                        saveOrUpdateBookData(data, uid);
                        if (downLoadListener != null) {
                            downLoadListener.onLoadSucess(data);
                        }

                    }
                } else {// 否则通知失败
                    if (downLoadListener != null) {
                        downLoadListener.onLoadFaild();
                    }
                }
            }
        };
        HttpRequest request =
                new HttpRequest(ShuqiApplication.getContext(), UrlManager.COLUMN_DOMAIN_SEARCH,
                        httpRequsetListener.getRequestUrl(), httpRequsetListener.setParams(),
                        httpRequsetListener);
        final YiSoDownCatalogParser catalogParser =
                new YiSoDownCatalogParser(bookId, sourceId, uid);
        request.setDataParseAdapter(catalogParser);
        if (isSync) {
            request.run();
        } else {
            MyTask.runInBackground(request, true);
        }
    }

    /**
     * 
     * 联网获取一搜章节目录
     * 
     * @param sourceId
     * @param bookId
     * @param uid
     */
    public static BookCataLog downloadYiSouOneChapter(final String bookId, final String sourceId,
            final String uid, final String chapterId) {
        HttpRequestListener httpRequsetListener = new HttpRequestListener() {
            @Override
            public List<BasicNameValuePair> setParams() {
                return null;
            }

            @Override
            public String getRequestUrl() {
                return Urls.getYiSouOneCatalogUrl(uid, bookId, sourceId, chapterId, 1);
            }

            @Override
            public void action(int actionCode, Object object) {
                if (actionCode == EventTypeConstants.EVENT_SUCCESS) {
                } else {// 否则通知失败
                }
            }
        };

        HttpRequest request =
                new HttpRequest(ShuqiApplication.getContext(), UrlManager.COLUMN_DOMAIN_SEARCH,
                        httpRequsetListener.getRequestUrl(), httpRequsetListener.setParams(),
                        httpRequsetListener);

        final YiSoDownCatalogParser catalogParser =
                new YiSoDownCatalogParser(bookId, sourceId, uid);
        request.setDataParseAdapter(catalogParser);
        request.run();
        BookData bookData = catalogParser.getParsedData();
        if (bookData != null) {
            List<BookCataLog> list = bookData.getInfos();
            if (list != null && list.size() > 0) {
                return list.get(0);
            }
        }
        return null;
    }

    /**
     * 
     * 联网获取书旗一章节目录
     * 
     * @param sourceId
     * @param bookId
     * @param uid
     */
    public static ShuqiOneChapterData downloadShuqiOneChapter(final String bookId,
            final String uid, final String chapterId) {

        HttpRequestListener httpRequsetListener = new HttpRequestListener() {
            @Override
            public List<BasicNameValuePair> setParams() {
                return null;
            }

            @Override
            public String getRequestUrl() {
                return Urls.getShuqiOneCatalogUrl(uid, bookId, chapterId);
            }

            @Override
            public void action(int actionCode, Object object) {
                if (actionCode == EventTypeConstants.EVENT_SUCCESS) {

                } else {// 否则通知失败
                }
            }
        };
        HttpRequest request =
                new HttpRequest(ShuqiApplication.getContext(), UrlManager.COLUMN_DOMAIN_READ,
                        httpRequsetListener.getRequestUrl(), httpRequsetListener.setParams(),
                        httpRequsetListener);

        final PayDownCatalogParser catalogParser = new PayDownCatalogParser(bookId, "", uid);
        request.setDataParseAdapter(catalogParser);
        request.run();

        BookData bookData = catalogParser.getParsedData();

        if (bookData != null) {
            ShuqiOneChapterData shuqiOneChapterData = new ShuqiOneChapterData();
            shuqiOneChapterData.hide = bookData.getHide();
            shuqiOneChapterData.readIsopen = bookData.getReadIsopen();
            List<BookCataLog> list = bookData.getInfos();

            if (list != null && list.size() > 0) {
                shuqiOneChapterData.boCataLog = list.get(0);
            }
            return shuqiOneChapterData;
        }
        return null;
    }

    static class ShuqiOneChapterData {
        BookCataLog boCataLog = null;
        String hide; // 是否隐藏Y隐藏，N正常
        int readIsopen = -1; // 阅读页开关 0阅读关，1阅读正常
    }

    static interface DownLoadListener {
        public void onLoadSucess(BookData bookData);

        public void onLoadFaild();
    }
}
